package com.zmsoft.boxy.sfg.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomUtils;
import org.cnsoft.framework.security.MD5SecurityHelper;
import org.cnsoft.framework.support.MyServiceSupport;
import org.cnsoft.framework.utils.EmptyHelper;

import com.zmsoft.boxy.sfg.cache.SFGGameInfoCacheService;
import com.zmsoft.boxy.sfg.cache.SFGPlayerInfoCacheService;
import com.zmsoft.boxy.sfg.player.BoxySFGPlayer;
import com.zmsoft.boxy.sfg.player.SFGGameConstants;
import com.zmsoft.boxy.sfg.player.SfgPlayerFriendDBO;
import com.zmsoft.persistent.sfg.Sfg661010PlayerFarm.Sfg661010PlayerFarmDBO;
import com.zmsoft.persistent.sfg.Sfg661021PlayerLand.Sfg661021PlayerLandDBO;
import com.zmsoft.persistent.sfg.Sfg661050PlayerFriend.Sfg661050PlayerFriendDBO;
import com.zmsoft.persistent.sfg.Sfg662020GameFarm.Sfg662020GameFarmDBO;
import com.zmsoft.persistent.sfg.Sfg662030GameExp.Sfg662030GameExpDBO;
import com.zmsoft.persistent.sfg.Sfg662040GameCrops.Sfg662040GameCropsDBO;
import com.zmsoft.persistent.sfg.Sfg662041GameCropsGrow.Sfg662041GameCropsGrowDBO;
import com.zmsoft.persistent.sfg.Sfg662060GameInteract.Sfg662060GameInteractDBO;

/**
 * 游戏推进器（后台任务处理）<br>
 * 依靠被动刷新和前台定时器来确认成长进度
 * 
 * @author ZmSoft
 * @version 0.1.0 2018/3/1
 * @since 0.1.0 2018/3/1
 * @see ApiManagerLoginController
 */
//@Service("SFGGameThrusterService")
//@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SFGGameThrusterServiceHelper extends MyServiceSupport implements SFGGameConstants {

	// 好友ID算法
	public static void preparePlayerFriend(BoxySFGPlayer player, SfgPlayerFriendDBO friend, Sfg661050PlayerFriendDBO playerFriend) throws Exception {
		// 确认好友ID
		if (player.getId().compareTo(friend.getPlayerFriendId()) > 0) {
			playerFriend.setPlayerId1(friend.getPlayerFriendId());
			playerFriend.setPlayerName1(friend.getPlayerFriendName());

			playerFriend.setPlayerId2(player.getId());
			playerFriend.setPlayerName2(player.getUserName());
		} else {
			playerFriend.setPlayerId1(player.getId());
			playerFriend.setPlayerName1(player.getUserName());

			playerFriend.setPlayerId2(friend.getPlayerFriendId());
			playerFriend.setPlayerName2(friend.getPlayerFriendName());
		}

		playerFriend.setId(MD5SecurityHelper.encrypt(playerFriend.getPlayerId1() + playerFriend.getPlayerId2()));
	}

	// 2.1.好友模式刷新
	public static void preparePlayerLand(SFGGameInfoCacheService sfgGameInfoCacheService, SFGPlayerInfoCacheService sfgPlayerInfoCacheService, BoxySFGPlayer player) throws Exception {
		List<Sfg661021PlayerLandDBO> playerLands = sfgPlayerInfoCacheService.loadPlayerLands(player);
		for (Sfg661021PlayerLandDBO land : playerLands) {
			preparePlayerLand(sfgGameInfoCacheService, sfgPlayerInfoCacheService, player, land);
		}
	}

	// 2.玩家模式刷新(自动成长)
	// 1土地种子/2幼苗发芽/3茁壮成长/4长大开花/5成熟结果
	public static void preparePlayerLand(SFGGameInfoCacheService sfgGameInfoCacheService, SFGPlayerInfoCacheService sfgPlayerInfoCacheService, BoxySFGPlayer player, Sfg661021PlayerLandDBO playerLand) throws Exception {
		// 用户农场信息
		Sfg661010PlayerFarmDBO playerFarm = sfgPlayerInfoCacheService.loadPlayerFarm(player);
		if (EmptyHelper.isEmpty(playerFarm) || EmptyHelper.isEmpty(playerLand)) {
			return;
		}
		// 判断土地状态1未开垦2未种植3成长中5成熟待收割9收割后未翻地
		if (THREE.equals(playerLand.getLandState()) == false) {
			return;
		}

		// 系统时间
		Long currentTimeMillis = System.currentTimeMillis();
		// 种植时间-秒
		// Long plantTime = playerLand.getPlantTime();// 开始时间
		// 减产系数
		int scope = 0;

		// 流失时间-秒
		Long lostTimeSecone = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - playerLand.getPlantTime());
		// 成熟需要时间秒
		Long cropsNeedTime = playerLand.getCropsNeedTime();
		// 作物类型
		Sfg662040GameCropsDBO gameCrop = sfgGameInfoCacheService.loadGameCropsData(SFG_GAME_FARM_TYPE, playerLand.getCropsId());

		// // 直接成熟，计算果实(离线时间>成熟需要时间秒)
		if (lostTimeSecone > cropsNeedTime) {
			// 当前阶段ID
			playerLand.setStageId(SIX);
			// 当前阶段名称
			playerLand.setStageName(SFG_Fini_StageName);

			// 当前阶段需要时间(秒) need_time
			playerLand.setNeedTime(0L);
			// 季数
			playerLand.setSeasonsNum(gameCrop.getMaxSeasonsNum());
			// 收获果实数目-最小值-最大值
			playerLand.setFruitMax(RandomUtils.nextLong(gameCrop.getFruitMin(), gameCrop.getFruitMax()));
			// 最大可偷取果实数目
			playerLand.setFruitStealMax((long) (playerLand.getFruitMax() * 0.1));
			// 剩余可偷取果实数目
			playerLand.setFruitStealLeft(playerLand.getFruitStealMax());
			// 果实单价-分
			playerLand.setFruitPrice(gameCrop.getFruitPrice());
			// 果实占用仓库容积大小
			playerLand.setFruitVolume(gameCrop.getFruitVolume());

			// 动作增加经验, 农场升级信息
//			preparePlayerFarmTodayExp(sfgGameInfoCacheService, sfgPlayerInfoCacheService, playerFarm, playerLand.getCropsExp());

			// 作物减产（1：种子->成熟，2：等级>5）
			if (playerLand.getCropsLevel() > 5) {
				// 1土地种子/2幼苗发芽/3茁壮成长/4长大开花/5成熟结果
				if (playerLand.getCropsState() < 2L) {
					scope = 35;
				} else if (playerLand.getCropsState() < 3L) {
					scope = 30;
				} else if (playerLand.getCropsState() < 4L) {
					scope = 25;
				} else if (playerLand.getCropsState() < 5L) {
					scope = 20;
				} else if (playerLand.getCropsState() < 6L) {
					scope = 15;
				}
			}

			// 计算减产
			peducePlayerLandCrops(sfgGameInfoCacheService, sfgPlayerInfoCacheService, playerLand, gameCrop, scope);
			// 用户数据保存
			sfgPlayerInfoCacheService.savePlayerFarm(playerFarm);
			sfgPlayerInfoCacheService.savePlayerLand(player, playerLand);
		} else {
			// 离线时间<=成熟需要时间秒
			// 判断处于哪个阶段
			// 流失时间-秒
			lostTimeSecone = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - playerLand.getCropsNeedTime1());// 1土地种子

			if (lostTimeSecone > 0) {
				Sfg662041GameCropsGrowDBO gameCropsGrowDBO = null;
				lostTimeSecone = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - playerLand.getCropsNeedTime2());// 2幼苗发芽
				if (lostTimeSecone > 0) {
					lostTimeSecone = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - playerLand.getCropsNeedTime2());// 3茁壮成长
					if (lostTimeSecone > 0) {
						lostTimeSecone = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - playerLand.getCropsNeedTime2());// 4长大开花
						if (lostTimeSecone > 0) {
							lostTimeSecone = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - playerLand.getCropsNeedTime2());// 5成熟结果
							if (lostTimeSecone > 0) {
								// 成熟阶段
							} else {
								gameCropsGrowDBO = sfgGameInfoCacheService.loadGameCropsGrowData(SFG_GAME_FARM_TYPE, playerLand.getCropsId(), FIVE);
								scope = 20;
							}
						} else {
							gameCropsGrowDBO = sfgGameInfoCacheService.loadGameCropsGrowData(SFG_GAME_FARM_TYPE, playerLand.getCropsId(), FOUR);
							scope = 15;
						}
					} else {
						gameCropsGrowDBO = sfgGameInfoCacheService.loadGameCropsGrowData(SFG_GAME_FARM_TYPE, playerLand.getCropsId(), THREE);
						scope = 10;
					}
				} else {
					gameCropsGrowDBO = sfgGameInfoCacheService.loadGameCropsGrowData(SFG_GAME_FARM_TYPE, playerLand.getCropsId(), TWO);
					scope = 5;
				}

				// 更新阶段数据
				if (EmptyHelper.isNotEmpty(gameCropsGrowDBO)) {
					// 当前阶段ID
					playerLand.setStageId(gameCropsGrowDBO.getId());
					// 当前阶段名称
					playerLand.setStageName(gameCropsGrowDBO.getStageName());
					// 土地图片
					playerLand.setLandPicUrl(gameCropsGrowDBO.getStagePicUrl());
					// 当前阶段需要时间(秒) need_time
					playerLand.setNeedTime(gameCropsGrowDBO.getNeedTime());

					// 动作增加经验, 农场升级信息
//					preparePlayerFarmTodayExp(sfgGameInfoCacheService, sfgPlayerInfoCacheService, playerFarm, gameCropsGrowDBO.getCropsExp());
					// 触发事件
					preparePlayerLandCropsState(sfgGameInfoCacheService, sfgPlayerInfoCacheService, playerLand, gameCrop, gameCropsGrowDBO);
					// 计算减产
					peducePlayerLandCrops(sfgGameInfoCacheService, sfgPlayerInfoCacheService, playerLand, gameCrop, scope);
					// 用户数据保存
					sfgPlayerInfoCacheService.savePlayerLand(player, playerLand);
					// 用户数据保存
					sfgPlayerInfoCacheService.savePlayerFarm(playerFarm);
				}
			}
		}

	}

	// 4.动作增加经验, 农场升级信息
	public static void preparePlayerFarmTodayExp(SFGGameInfoCacheService sfgGameInfoCacheService, SFGPlayerInfoCacheService sfgPlayerInfoCacheService, Sfg661010PlayerFarmDBO playerFarm, long exp) throws Exception {
		// 获得当前等级
		long level = playerFarm.getFarmLevel() + 1;

		// 获得每日经验配置信息
		Sfg662030GameExpDBO gameExpData = sfgGameInfoCacheService.loadGameExpData(SFG_GAME_FARM_TYPE, level);
		if (EmptyHelper.isNotEmpty(gameExpData)) {
			long expDay = playerFarm.getTodayExp() + exp;
			if (expDay > gameExpData.getCurFarmMaxExp()) {
				// 超过每日上限
				return;
			}
			// 动作增加经验
			playerFarm.setTodayExp(expDay);
			playerFarm.setTotalExp(playerFarm.getTotalExp() + exp);
		}

		// 农场升级
		if (EmptyHelper.isNotEmpty(gameExpData)) {
			long expLeft = playerFarm.getTotalExp() - playerFarm.getNextExp();
			if (expLeft < 0) {
				// 经验不足
				return;
			}
			// 完成升级，经验扣除
			playerFarm.setTotalExp(expLeft);
			playerFarm.setFarmLevel(level);

			// 设置下一级
			level = level + 1;
			Sfg662020GameFarmDBO gameFarmData = sfgGameInfoCacheService.loadGameFarmData(SFG_GAME_FARM_TYPE, level);
			if (EmptyHelper.isNotEmpty(gameFarmData)) {
				playerFarm.setNextExp(gameFarmData.getNeedFarmExp());
			} else {
				playerFarm.setNextExp(Long.MAX_VALUE);
			}
		}
	}

	// 3.作物减产
	// scope(0~99)===>>> >50:增产，<50减产
	public static void peducePlayerLandCrops(SFGGameInfoCacheService sfgGameInfoCacheService, SFGPlayerInfoCacheService sfgPlayerInfoCacheService, Sfg661021PlayerLandDBO playerLand, Sfg662040GameCropsDBO gameCrop, int scope) throws Exception {
		// 判断处理模式
		if (scope > 50) {
			scope = RandomUtils.nextInt(0, (scope - 50));
			playerLand.setFruitMax(Math.round(gameCrop.getFruitMax() * (1 + scope * 0.01)));
		} else {
			scope = RandomUtils.nextInt(0, scope);
			playerLand.setFruitMax(Math.round(gameCrop.getFruitMax() * (1 - scope * 0.01)));
		}
	}

	// 1.事件触发(允许玩家执行哪些交互)
	public static void preparePlayerLandCropsState(SFGGameInfoCacheService sfgGameInfoCacheService, SFGPlayerInfoCacheService sfgPlayerInfoCacheService, Sfg661021PlayerLandDBO playerLand, Sfg662040GameCropsDBO gameCrop, Sfg662041GameCropsGrowDBO gameCropsGrowDBO) throws Exception {
		if (TWO.equals(gameCropsGrowDBO.getActionFlag()) == false) {
			return;
		}

		// 物品图片
		playerLand.setLandPicUrl(gameCropsGrowDBO.getStagePicUrl());

		String[] actions = gameCropsGrowDBO.getActionIds().split(COMMA);
		int index = RandomUtils.nextInt(0, actions.length);
		if (index >= actions.length) {
			return;
		}

		// 允许玩家采用的交互动作配置（一个阶段只能做一次）
		Sfg662060GameInteractDBO gameInteract = sfgGameInfoCacheService.loadGameInteractData(GAME_INTERACT, actions[index]);
		if (EmptyHelper.isEmpty(gameInteract)) {
			return;
		} else {
			// 阶段互动ID
			playerLand.setActionId(gameInteract.getId());
			// 阶段互动名称
			playerLand.setActionName(gameInteract.getActionName());
			// 功能操作指令
			playerLand.setActionCommandPage(gameInteract.getActionCommandPage());
			// 服务操作指令
			playerLand.setActionCommandApi(gameInteract.getActionCommandApi());
		}

		// 1土地种子/2幼苗发芽/3茁壮成长/4长大开花/5成熟结果
		playerLand.setCropsState(gameCropsGrowDBO.getStageSort());
		// 阶段整理
		if (playerLand.getCropsState() > 5L) {
			// 剩余浇水数目
			playerLand.setLeftWatering(gameCropsGrowDBO.getLeftWatering());
			// 剩余杀虫数目
			playerLand.setLeftInsect(gameCropsGrowDBO.getLeftInsect());
			// 剩余施肥数目
			playerLand.setLeftFertilize(gameCropsGrowDBO.getLeftFertilize());
		} else if (playerLand.getCropsState() > 4L) {// 成熟结果
			// 剩余浇水数目
			playerLand.setLeftWatering(gameCropsGrowDBO.getLeftWatering());
			// 剩余杀虫数目
			playerLand.setLeftInsect(gameCropsGrowDBO.getLeftInsect());
			// 剩余施肥数目
			playerLand.setLeftFertilize(gameCropsGrowDBO.getLeftFertilize());
		} else if (playerLand.getCropsState() > 3L) {// 长大开花
			// 剩余浇水数目
			playerLand.setLeftWatering(gameCropsGrowDBO.getLeftWatering());
			// 剩余除草数目
			playerLand.setLeftWeeding(gameCropsGrowDBO.getLeftWeeding());
			// 剩余施肥数目
			playerLand.setLeftFertilize(gameCropsGrowDBO.getLeftFertilize());
		} else if (playerLand.getCropsState() > 2L) {// 茁壮成长
			// 剩余浇水数目
			playerLand.setLeftWatering(gameCropsGrowDBO.getLeftWatering());
			// 剩余除草数目
			playerLand.setLeftWeeding(gameCropsGrowDBO.getLeftWeeding());
			// 剩余施肥数目
			playerLand.setLeftFertilize(gameCropsGrowDBO.getLeftFertilize());
		} else if (playerLand.getCropsState() > 1L) {// 幼苗发芽
			// 剩余浇水数目
			playerLand.setLeftWatering(gameCropsGrowDBO.getLeftWatering());
			// 剩余施肥数目
			playerLand.setLeftFertilize(gameCropsGrowDBO.getLeftFertilize());
		} else {// 土地种子
				// 剩余浇水数目
			playerLand.setLeftWatering(gameCropsGrowDBO.getLeftWatering());

//			// 农场物品配置信息
//			Sfg662040GameCropsDBO gameCrop = sfgGameInfoCacheService.loadGameCropsData(SFG_GAME_FARM_TYPE, playerLand.getCropsId());
			// 最大果实数目
			playerLand.setFruitMax(gameCrop.getFruitMax());
			// 最大可偷取果实数目
			playerLand.setFruitStealMax(Math.round(gameCrop.getFruitMax() * 0.1));
			// 剩余可偷取果实数目
			playerLand.setFruitStealLeft(playerLand.getFruitStealMax());
			// 果实单价-分
			playerLand.setFruitPrice(gameCrop.getFruitPrice());
			// 果实占用仓库容积大小
			playerLand.setFruitVolume(gameCrop.getFruitVolume());
		}
		// 可以获得经验数目
		playerLand.setCropsExp(gameCropsGrowDBO.getCropsExp());
	}

}
